package com.wectrls.common.utils;

import com.wectrls.config.exceptiom.BindingResultHasFieldErrorsException;
import com.wectrls.enums.RESPONSE_ENUM;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenjian
 * @Package
 * @Description:
 * @date 2019/7/1 11:49
 */

public class BindResultUtils {


    /**
     * 检查所有字段，获取所有错误信息
     *
     * @param bindingResult
     * @return
     */
    public static void checkBindingResult(BindingResult bindingResult) {
        Map<String, String> map = new HashMap<>();
        if (bindingResult.getErrorCount() > 0) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
        }
        if (map.size() > 0) {
            throw new BindingResultHasFieldErrorsException("非法数据", RESPONSE_ENUM.FAIL_500.getCode(), map);
        }

    }
}
